#!/usr/bin/env python
"""
自动修复代码风格问题的脚本
"""
import os
import re
import sys

def fix_blank_lines(file_path):
    """修复空白行中的空格"""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    fixed_lines = []
    for line in lines:
        # 修复空白行中的空格
        if line.strip() == '' and line != '\n':
            fixed_lines.append('\n')
        else:
            fixed_lines.append(line)
    
    # 确保文件以换行符结尾
    if fixed_lines and not fixed_lines[-1].endswith('\n'):
        fixed_lines[-1] += '\n'
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(fixed_lines)

def fix_unused_imports(file_path):
    """修复未使用的导入"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 修复常见的未使用导入
    content = re.sub(r'from flask import url_for\n', '', content)
    content = re.sub(r'from flask import redirect\n', '', content)
    content = re.sub(r'from datetime import date\n', '', content)
    content = re.sub(r'from app.models import get_db\n', '', content)
    
    # 修复多个导入在同一行的情况
    content = re.sub(r'from flask import url_for, redirect\n', 'from flask import redirect\n', content)
    content = re.sub(r'from flask import redirect, url_for\n', 'from flask import redirect\n', content)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)

def fix_undefined_variables(file_path):
    """修复未定义的变量"""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    fixed_lines = []
    for line in lines:
        # 修复未定义的db变量
        if 'db.' in line and 'db = ' not in line and 'from app import db' not in ''.join(fixed_lines[-10:]):
            # 如果在最近10行中没有导入db，则添加导入
            if not any('from app import db' in l for l in fixed_lines):
                fixed_lines.insert(0, 'from app import db\n')
        fixed_lines.append(line)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(fixed_lines)

def main():
    """主函数"""
    # 需要修复的文件列表
    files_to_fix = [
        'app/services/project_service.py',
        # 'app/services/opportunity_service.py',  # 商机服务已删除
        'app/static/__init__.py',
        'app/templates/__init__.py',
        'app/utils/__init__.py',
        'app/utils/helpers.py',
        'app/utils/validators.py'
    ]
    
    for file_path in files_to_fix:
        if os.path.exists(file_path):
            print(f"正在修复: {file_path}")
            fix_blank_lines(file_path)
            fix_unused_imports(file_path)
            fix_undefined_variables(file_path)
        else:
            print(f"文件不存在: {file_path}")
    
    print("代码风格问题修复完成！")

if __name__ == '__main__':
    main()